import { CommonForm } from "@/pages/OrderModule/common/components/CommonForm";
import { CommonModal } from "@/pages/OrderModule/common/components/CommonModal";
import { CommonTable } from "@/pages/OrderModule/common/components/CommonTable";
import Typography from "@/pages/OrderModule/common/components/Typography";
import { Alert, Form, message, InputNumber, Popover } from "antd";
import OrderAreaRadioGroup from "../../components/OrderAreaRadioGroup1";
import OrderNumberCount from "../../components/OrderNumberCount";
import { useState, useRef } from "react";
import FuzzyQueryStore from "@/components/FuzzyQueryStore";
import { getzjfstoreList, supplierMatchOp } from "../../../../services";
import CommonPlatformImg from "@/components/CommonImg/PlatformComponent";
import CommonLoading from "@/components/CommonLoading";
import { find, cloneDeep, uniqBy } from "lodash";
import Iconfont from "@/components/IconFont";

/** 供应商匹配 */
function SupplierMatchingModal(props) {
	const { searchForm, orderList, selectKeys, handleCancel, handleOk } = props;
	const [showGoodsList, setShowGoodsList] = useState([]); //待审核，异常未匹配的商品
	const [showNumber, setShowNumber] = useState({
		10: 0,
		30: 0
	});
	const [loading, setLoading] = useState(false);

	const filterIds = useRef(undefined);

	const [form] = Form.useForm();

	const onOk = async () => {
		if (!showNumber.total) {
			return message.info("暂无可处理的订单！");
		}
		const arr = [];
		showGoodsList.forEach(item => {
			if ("oldSupplierId" in item) {
				arr.push({
					oldSupplierId: item.oldSupplierId,
					storeId: item.storeId,
					storeName: item.storeName,
					sysGoodsId: item.sysGoodsId,
					goodsPrice: item.goodsPrice,
					shopCode: item.shopCode
				});
			}
		});
		// if (arr.length != showGoodsList.length) {
		// 	return message.info("供应商为必填项，不能为空");
		// }
		setLoading(true);
		const { msg, success } = await supplierMatchOp({
			goodsMatchStoreList: uniqBy(arr, 'sysGoodsId'),
			orderIds: filterIds.current || selectKeys,
            industrialBeltFlag: INDUSTRIAL_BELT_FLAG
		});
		setLoading(false);
		if (success) {
			message.success(msg);
			handleOk();
		}
	};

	//供应商改动
	const handleStoreChange = (val, record, index, obj) => {
		const arr = cloneDeep(showGoodsList);
		if (val) {
			arr[index]["storeId"] = val;
			arr[index]["storeName"] = obj.storeName;
			arr[index]["oldSupplierId"] = record.storeId;
			arr[index]["shopCode"] = obj.shopCode;
		}
		setShowGoodsList(arr);
	};

	//更改商品价格
	const handlePriceChange = (e, index) => {
		const val = e;
		// 匹配正整数、小数（不包括0）
		const reg = /^(?!\.0*$)\d+(\.\d+)?$/;
		if (val == showGoodsList[index].goodsPrice) {
			return;
		}
		if (reg.test(val)) {
			const arr = cloneDeep(showGoodsList);
			arr[index].goodsPrice = val;
			setShowGoodsList(arr);
		} else {
			message.info("请输入正数");
		}
	};

	const columns = [
		{
			title: "系统商品",
			dataIndex: "name",
			key: "name",
			render(text, record) {
				return (
					<span>
						<div style={{ display: "flex" }}>
							<CommonPlatformImg img={record.sysGoodsImage} />
							<div style={{ marginLeft: "8px" }}>
								<div>{record.sysGoodsName}</div>
								<div>{record.sysGoodsSpec}</div>
							</div>
						</div>
					</span>
				);
			}
		},
		{
			title: "商品编码",
			dataIndex: "sysSkuCode",
			key: "sysSkuCode"
		},
		{
			title: "款式编码",
			dataIndex: "sysSpuCode",
			key: "sysSpuCode"
		},
		{
			title: "匹配供应商",
			dataIndex: "storeName",
			key: "storeName",
			render(text, record, index) {
				return (
					<FuzzyQueryStore
						storeName={text}
						queryData={getzjfstoreList}
						storeId={record.storeId}
						onChange={(val, a, obj) => handleStoreChange(val, record, index, obj)}
						width={140}
					/>
				);
			}
		},
		{
			title: (
				<Popover
					content={
						<div style={{ width: "200px" }}>
							<p>采购价：优先取填写的供应商价格，未填写则优先取系统商品的成本价，无成本价则默认0.01</p>
						</div>
					}
				>
					<div>
                        采购价
						<Iconfont type="iconwenhao1" />
					</div>
				</Popover>
			),
			dataIndex: "goodsPrice",
			key: "goodsPrice",
			render: (text, _, index) => (
				<div>
					<InputNumber precision="2" min={0} value={text} onChange={e => handlePriceChange(e, index)} />
				</div>
			)
		}
	];

	const orderAreaRadioProps = {
		searchForm,
		selectKeys,
		orderList,
		states: [10, 30],
		title: "仅限待审核和异常状态的订单",
		updateShowNumer(obj = {}, ids) {
			const arr = [];
			const newArr = orderList.filter(item => item.runVolume != true);
			if (ids.length) {
				//所有符合条件
				ids.map(item => {
					const newObj = find(newArr, ["id", item]);
					newObj?.goodsList.map(z => {
						if (z.isMatch != 1) {
							arr.push({ ...z, goodsPrice: null });
						}
					});
				});
			}
			setShowGoodsList(arr);
			filterIds.current = ids;
			setShowNumber(obj);
		}
	};

	return (
		<CommonModal title={{ title: "供应商匹配" }} open={true} width="870px" onOk={onOk} onCancel={handleCancel}>
			<Alert showIcon message={<Typography as="s1">只针对未匹配的商品可以进行供应商匹配</Typography>} />
			<CommonForm
				formProps={{
					form
				}}
				columns={[
					{
						name: "radio-group",
						slot: <OrderAreaRadioGroup wrapStyle={{ marginTop: 16 }} {...orderAreaRadioProps} />
					},
					{
						block: (
							<OrderNumberCount
								data={[
									{ label: "待审核", value: showNumber[10], type: "warning" },
									{ label: "异常", value: showNumber[30], type: "error" }
								]}
							/>
						)
					}
				]}
			></CommonForm>
			<CommonTable
				scroll={false}
				bordered
				style={{ marginTop: 16 }}
				dataSource={showGoodsList}
				columns={columns}
				pagination={false}
				rowKey={"id"}
			/>

			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default SupplierMatchingModal;
